package com.egrand.sweetapi.plugin.db.configure;

import com.egrand.sweetapi.starter.db.toolkit.CryptoUtils;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * EgdTenantDataSourceProperties
 */
@Slf4j
@Getter
@Setter
@ConfigurationProperties(prefix = EgdTenantDataSourceProperties.PREFIX)
public class EgdTenantDataSourceProperties {

    /**
     * 加密正则
     */
    private static final Pattern ENC_PATTERN = Pattern.compile("^ENC\\((.*)\\)$");

    public static final String PREFIX = "spring.datasource.tenant";

    /**
     * 定时拉取数据源表达式
     */
    private String cron = "";

    /**
     * 数据库连接
     */
    private String url = "";
    /**
     * 用户名
     */
    private String username = "";
    /**
     * 密码
     */
    private String password = "";

    /**
     * 解密公匙(如果未设置默认使用全局的)
     */
    private String publicKey;

    public String getUrl() {
        return decrypt(url);
    }

    public String getUsername() {
        return decrypt(username);
    }

    public String getPassword() {
        return decrypt(password);
    }

    /**
     * 字符串解密
     */
    private String decrypt(String cipherText) {
        if (StringUtils.hasText(cipherText)) {
            Matcher matcher = ENC_PATTERN.matcher(cipherText);
            if (matcher.find()) {
                try {
                    return CryptoUtils.decrypt(publicKey, matcher.group(1));
                } catch (Exception e) {
                    log.error("DynamicDataSourceProperties.decrypt error ", e);
                }
            }
        }
        return cipherText;
    }
}
